package com.luminary.demo.authentication.core.security;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.luminary.demo.authentication.model.security.UserMeta;
import com.luminary.demo.user.dao.UserDao;
import com.luminary.security.sso.authentication.SsoUserDetailsService;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 获取用户信息，用来鉴权
 * 
 * @author wulinfeng
 *
 */
@Slf4j
@RefreshScope
@Service
public class UserDetailsServiceImpl extends SsoUserDetailsService {

	@Autowired
	private UserDao userDao;
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	@Autowired
	private RedisTemplate<Object, Object> redisTemplate;
	
	@Override
	public UserInfo getPasswordByUsername(String username) {
		return getUserInfo(username);
	}

	@Override
	public UserInfo isExistsUser(String username) {
		return getUserInfo(username);
	}
	
	@Override
	public PasswordEncoder getPasswordEncoder() {
		return passwordEncoder;
	}

	@Override
	public RedisTemplate<Object, Object> getRedisTemplate() {
		return redisTemplate;
	}

	@Override
	public User convert(UserComponent userComponent) {
		
		Gson gson = new Gson();
		User user = userComponent.getUser();
		UserInfo userInfo = userComponent.getUserInfo();
		UserMeta targetUser = gson.fromJson(userInfo.getJson(), UserMeta.class);
		UserMeta sourceUser = new UserMeta(targetUser.getUsername(), userInfo.getPassword(), user.getAuthorities());
		sourceUser.setExtraInfo(targetUser.getExtraInfo());
		
		return sourceUser;
		
	}
	
	private UserInfo getUserInfo(String username) {
		
		Gson gson = new Gson();
		
		com.luminary.demo.user.model.po.User user = userDao.selectByUsername(username);
		UserMeta userMeta = new UserMeta(username);
		
		BeanUtils.copyProperties(user, userMeta);
		
		UserInfo userInfo = new UserInfo();
		userInfo.setPassword(user.getPassword());
		userInfo.setJson(gson.toJson(userMeta));
		if("admin".equals(username))
			userInfo.setAuthorities("ADMIN");
			
		return userInfo;
		
	}
	
}
